import smtplib
import os
import zmail


class Email_Option():
    def __init__(self, sender_email, sender_password):

        self.sender_email = sender_email
        self.sender_password = sender_password

    def send_email(self, recipients: list, subject: str, body: str, attachments=None, cc=None):
        """
        发送邮件
        :param recipients: 列表，收件人邮箱
        :param subject: 标题
        :param body: 内容
        :param attachments: 附件
        :param cc: 抄送
        :return:
        """
        if attachments is not None:
            attachments = self.get_attachment_paths(attachments)
        else:
            attachments = []

        try:
            mail = {
                'subject': subject,  # 邮件标题
                'content_text': body,  # 邮件内容
                'attachments': attachments,  # 本地文件的绝对路径
            }

            server = zmail.server(self.sender_email, self.sender_password, debug=True)

            server.send_mail(recipients, mail, cc=cc)
            print(f'主题为《{subject}》的邮件发送成功！收件人：{", ".join(recipients)}')
            return True
        except smtplib.SMTPException as k:
            print(f'主题为《{subject}》的邮件发送成功！收件人：{", ".join(recipients)}')
            return True
        except Exception as e:
            print("发送邮件时出错:", e)
            return False

    def get_attachment_paths(self, attachments):
        """
        列出附件绝对地址的函数
        :param attachments:
        :return:
        """
        attachment_paths = []
        if attachments:
            if isinstance(attachments, list):
                for attachment in attachments:
                    if os.path.isfile(attachment):
                        attachment_paths.append(os.path.abspath(attachment))
                    elif os.path.isdir(attachment):
                        for file_name in os.listdir(attachment):
                            file_path = os.path.join(attachment, file_name)
                            if os.path.isfile(file_path):
                                attachment_paths.append(os.path.abspath(file_path))
            elif os.path.isfile(attachments):
                attachment_paths.append(os.path.abspath(attachments))
            elif os.path.isdir(attachments):
                for file_name in os.listdir(attachments):
                    file_path = os.path.join(attachments, file_name)
                    if os.path.isfile(file_path):
                        attachment_paths.append(os.path.abspath(file_path))
        return attachment_paths
